import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';

class DependenciesProvider implements vscode.WebviewViewProvider {
  context: vscode.ExtensionContext;
  constructor(context: vscode.ExtensionContext) {
    this.context = context;
  }

  refreshStore(store: any) {
    const openEditors = vscode.window.visibleTextEditors;

    if (openEditors.length === 2) {
      store.leftContentLength = openEditors[0].document.getText().replace(/[\r\n]/g, '').length;
      store.leftContentArr = openEditors[0].document.getText().replace(/[\r]/g, '').split('\n');
      store.rightContentLength = openEditors[1].document.getText().replace(/[\r\n]/g, '').length;
      store.rightContentArr = openEditors[1].document.getText().replace(/[\r]/g, '').split('\n');
      store.rightProgressLength = 0;

      for (let i = 0; i < store.leftContentArr.length; i++) {
        const elementL = store.leftContentArr[i];
        for (let j = 0; j < store.rightContentArr.length; j++) {
          const elementR = store.rightContentArr[j];
          if (i === j) {
            if (elementL.replace('\r', '') === elementR.replace('\r', '')) {
              store.rightProgressLength += elementL.length;
            } else {
              for (let x = 0; x < elementL.length; x++) {
                const cL = elementL[x];
                for (let y = 0; y < elementR.length; y++) {
                  const cR = elementR[y];
                  if (x === y) {
                    if (cL === cR) {
                      store.rightProgressLength += 1;
                    }else{
                      break;
                    }
                  }
                }
              }
            }
          }
        }
      }

      store.rightProgress = (store.rightProgressLength / store.leftContentLength * 100).toFixed(2);

    }
    return store;
  }


  // 实现 resolveWebviewView 方法，用于处理 WebviewView 的创建和设置
  resolveWebviewView(webviewView: vscode.WebviewView, context: vscode.WebviewViewResolveContext<unknown>, token: vscode.CancellationToken): void | Thenable<void> {
    // 配置 WebviewView 的选项
    webviewView.webview.options = {
      enableScripts: true,
      enableCommandUris: true,
      localResourceRoots: [this.context.extensionUri]
    };

    // console.debug(path.join(__dirname, 'pages/fileSync.html'));


    // 获取本地 JavaScript 文件的 URI
    const localScriptUri = vscode.Uri.file(path.join(__dirname, 'pages/main.js'));
    // console.debug('locaScriptUri', localScriptUri);
    const webviewScriptUri = webviewView.webview.asWebviewUri(localScriptUri);
    // console.debug('webviewScriptUri', webviewScriptUri);

    // 设置 WebviewView 的 HTML 内容，可以在这里指定要加载的网页内容
    webviewView.webview.html =
      fs.readFileSync(path.join(__dirname, 'pages/fileSync.html'))
        .toString()
        .replace('main.js', webviewScriptUri.toString());

    // console.log(webviewView.webview.html);

    let store = {
      editorLength: 0,
      leftContentLength: 0,
      leftContentArr: [""],
      rightContentLength: 0,
      rightContentArr: [""],
      rightProgressLength: 0, // 0%
      rightProgress: "0", // 0%
    };



    // 在输出面板中打印编辑器信息
    // openEditors.forEach(editor => {
    //   console.log(`Editor: ${editor.document.fileName}`);
    //   // console.log(`Editor: ${editor.document.getText()}`);
    // });


    // 在扩展中
    webviewView.webview.onDidReceiveMessage(message => {
      switch (message.command) {
        case 'v2cGetEditorStore':

          // 对比文档相似进度
          // 获取所有打开的编辑器
          store = this.refreshStore(store);

          // vscode.commands.executeCommand('mdc.showOpenEditors');
          let copy = JSON.parse(JSON.stringify(store));
          delete copy.leftContentArr;
          delete copy.rightContentArr;
          // 在扩展中
          webviewView.webview.postMessage({ command: 'v2cGetEditorStoreRes', data: JSON.stringify(copy) });
          break;
      }
    });




  }
}

export default DependenciesProvider;
